package com.wenlin.customerservice.domain;

import com.google.common.hash.Hashing;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

/***
 *  Created with IntelliJ IDEA.
 *  User:  wenlin
 *  Date:  2018/2/9
 *  Time:  17:14
 *  Description:
 **/
public class Test {
    //遍历map，拼接参数
    private static String getParams(Map<String,String> map) {
        StringBuffer stringBuffer = new StringBuffer();
        SortedSet<String> params = new TreeSet();
        map.entrySet().forEach((t) -> {
            if (!(t.getKey()).equals("sign")) {
                try {
                    params.add(String.format("%s=%s", URLEncoder.encode(t.getKey(), "UTF-8"), URLEncoder.encode(map.get(t.getKey()), "UTF-8")));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
        params.forEach((n) -> {
            stringBuffer.append("&" + n);
        });
        stringBuffer.delete(0, 1);
        return stringBuffer.toString();
    }
    //url+params+appSecret拼接，md5加密,生成最后的签名字符串sign
    private static String validSecret(String appSecret, String path, String params) {
        String toSign = String.format("%s?%s%s", path, params, appSecret);
        System.out.println(MD5(toSign).toLowerCase());
        return Hashing.md5().newHasher().putString(toSign, Charset.defaultCharset()).hash().toString();
    }
    public static void main(String[] args) {

        //用户秘钥，由开发人员统一分配
        String appSecret = "mdminbaseyto";
         //参数示例，往map存入customerCode 为K99902244
          Map<String,String> map = new HashMap<>();
          map.put("customerCode","K99902244");
         //拼接参数
        String params  = getParams(map);
         //接口基本地址
        String path = "/mdminbase/customer/balance";
        //加密
        String sign = validSecret(appSecret,path,params);
        System.out.println(sign);

    }
    /***
     *  User:  wenlin
     *  Date:  2018/2/28
     *  Time:  10:26
     *  Description:md5加密
     **/
    public static String MD5(String s){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(s.getBytes("utf-8"));
            return toHex(bytes);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static String toHex(byte[] bytes) {

        final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (int i=0; i<bytes.length; i++) {
            ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
        }
        return ret.toString();
    }
}
